package com.pro.bl.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.pro.bl.dto.PersonDTO;
import com.pro.bl.dto.PersonDTO.Status;
import com.pro.dl.dao.service.PersonDao;
import com.pro.dl.exception.StorageException;
import com.pro.dl.exception.UserDoesNotExists;
import com.pro.dl.pojo.Person;

public class AuthenticationServiceImpl {

	static Logger logger = LogManager
			.getLogger(AuthenticationServiceImpl.class);

	// Autowired
	PersonDao personDao;

	public PersonDTO authenticateUser(Person person) throws StorageException {

		Status status = null;
		Person result = personDao.searchPersonByUserName(person.getUserName());
		if (result == null) {
			status = Status.NO_USERNAME;
		} else if (!result.isVerified()) {
			status = Status.NOT_VERIFIED;
		} else if (result.isBlocked()) {
			status = Status.BLOCKED;
		} else if (!result.getPassword().equals(person.getPassword())) {
			status = Status.PASSWORD_MISMATCH;
			result.setPassword(null);
		}
		return new PersonDTO(result, status);
	}

	public Status overridePassword(String userName, String password)
			throws StorageException {
		Status status = null;
		try {
			personDao.overridePassword(userName, password);
		} catch (UserDoesNotExists e) {
			logger.error("User does not exists for password override ", e);
			status = Status.NO_USERNAME;
		} catch (Exception e) {
			logger.error("There is exception in database layer ", e);
			status = Status.INFRASTRUCTURE_ERROR;
		}
		return status;
	}

	// should throw here password mismatch exception.
	public Status changePassword(String userName, String oldPassword,
			String newPassword) throws StorageException, UserDoesNotExists {
		Status status = null;
		Person result = personDao.searchPersonByUserName (userName);
		if (result.getPassword().equals(oldPassword)) {
			result.setPassword(newPassword);
			personDao.overridePassword(userName, newPassword);
			status = Status.SUCCESSFUL;
		}
		return status;
	}

	public Status matchPassword(String userName, String password)
			throws StorageException {
		Status status = null;
		Person result = personDao.searchPersonByUserName(userName);
		if (result == null) {
			status = Status.NO_USERNAME;
		} else if (result.getPassword().equals(password)) {
			status = Status.SUCCESSFUL;
		} else {
			status = Status.PASSWORD_MISMATCH;
		}

		return status;
	}

}
